#!/usr/bin/env bash

set -e

APPID=$1
VERSION=$2
BUILD=$3
LAYER=$4
WORKDIR=$APPID
SMALLER_APPID=$(echo "$APPID" | tr '[:upper:]' '[:lower:]')

echo "Downloading app data from flathub"
ostree --repo="$FLATHUB_CACHE" pull flathub "$COMMIT_ID"
rm -rf "$WORKDIR" && mkdir -p "$WORKDIR"
echo "Extracting app data to $WORKDIR/flatpak"
ostree --repo="$FLATHUB_CACHE" checkout "$COMMIT_ID" "$WORKDIR/flatpak"

FLATPAK_COMMAND=$(grep '^command=' $WORKDIR/flatpak/metadata | awk -F'=' '{print $2}')
FLATPAK_RUNTIME=$(grep '^runtime=' "$WORKDIR"/flatpak/metadata | awk -F'=' '{print $2}' | awk -F'/' '{print $1}')
FLATPAK_RUNTIME_VERSION=$(grep '^runtime=' "$WORKDIR"/flatpak/metadata | awk -F'=' '{print $2}' | awk -F'/' '{print $3}')

LINGLONG_BASE_NAME="org.deepin.base.flatpak.$(echo "$FLATPAK_RUNTIME"|awk -F'.' '{print $2}')"
LINGLONG_BASE_VERSION="$(echo "${FLATPAK_RUNTIME_VERSION/.0/.}.0.0.0" | awk -F'[-.]' 'BEGIN {OFS="."} {print $1,$2,$3}')"

if [[ -n $BASE ]];
then
    LINGLONG_BASE_NAME=$BASE
fi

if [[ -n $BASE_VERSION ]];
then
    LINGLONG_BASE_VERSION=$BASE_VERSION
fi

# 替换 desktop 文件里面 Exec 的 /app 开头路径
for desktop in `ls -1 $WORKDIR/flatpak/files/share/applications/*desktop`
do
    # DESKTOP_PATH=$WORKDIR/flatpak/files/share/applications/$desktop
    EXEC_OLD=$(grep -e '^Exec=.*' "$desktop" | head -n 1 | cut -d "=" -f 2- | sed -e 's|%.||g')
    if echo "$EXEC_OLD" | grep -q "/app";
    then
        # replace flatpak /app to linglong /opt/apps/$APPID/files
        EXEC=$(echo $EXEC_OLD | sed "s|/app|/opt/apps/$APPID/files|g")
        sed -i "/Exec*/c\\Exec=$EXEC" "$desktop"
    else
        EXEC=$EXEC_OLD
    fi
done

BIN_FILE=${EXEC_OLD%% *}
if [[ $BIN_FILE == /* ]];
then
    BIN_FILE_PATH=$(echo "$BIN_FILE" | sed "s|/app|$APPID/flatpak/files|g")
else
    BIN_FILE_PATH=$APPID/flatpak/files/bin/$BIN_FILE
fi

cat > "$WORKDIR"/linglong.yaml <<EOF
version: "1"
package:
  id: $SMALLER_APPID
  name: $SMALLER_APPID
  version: $VERSION
  kind: app
  description: flatpak runtime environment on linglong

command: [$FLATPAK_COMMAND]
base: $LINGLONG_BASE_NAME/$LINGLONG_BASE_VERSION

build: |
  mkdir \$PREFIX/etc
  cp profile \$PREFIX/etc
  cp -rf flatpak/files/* \$PREFIX
EOF

cat > $WORKDIR/profile<<EOF
#!/bin/sh
# bind /opt/apps/$APPID/files to /app
ln -s "/opt/apps/\$LINGLONG_APPID/files" /run/linglong/app
EOF

if $BUILD;
then
    cd "$WORKDIR"
    ll-builder build

    if $LAYER;
    then
        ll-builder export --layer
    else
        ll-builder export
    fi
fi

